<template>
	<view class="container">
		<!-- <view  style="color: #CCCCCC;text-align: center;width: 100%;height: 500upx;line-height: 500upx;font-size: 32upx;"> 暂无数据</view> -->
		<!-- 空白页 -->
		<view v-if="empty===true" class="empty">
			<image src="/static/emptyCart.jpg" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				空空如也
				<navigator class="navigator" v-if="hasLogin" url="../index/index" open-type="switchTab">随便逛逛></navigator>
			</view>
			<view v-else class="empty-tips">
				空空如也
				<!-- #ifdef MP-WEIXIN -->
				<view class="navigator" @click="navToLoginWx">去登陆></view>
				<!-- #endif -->
				<!-- #ifndef MP-WEIXIN -->
				<view class="navigator" @click="navToLogin">去登陆></view>
				<!-- #endif -->
			</view>
		</view>
		<view v-else>
			<!-- <uni-notice-bar :show-get-more="true" color="#F76260" :show-icon="true" :single="true" more-text="查看更多" text="年末大礼：uni-app1.4 新增百度、支付宝小程序。插件市场重磅上线！" @getmore="getMore" /> -->
			
			 
			 
			<!-- 列表 -->
			<view class="cart-list">
				
				<block v-for="(item, index) in cartList" :key="item.ID">
					
					<view
						class="cart-item" 
						:class="{'b-b': index!==cartList.length-1}"
					>
						<view class="image-war">
							<image :src="img+item.THUMB"
							 mode="aspectFill" 
							 @click="see(item.GOODSID)"
							 ></image>
							<view 
								v-if="item.STATE==2"
								class="yticon icon-xuanzhong2 checkbox"
								:class="{checked: item.checked}"
								@click="check('item', index)"
							></view>
							
						</view>
						<view class="item-right"  >
							<text class="clamp title">{{item.TITLE}}</text>
							<text class="attr">{{item.GOODSSPEC}}</text>
							<view class="item1">
								
								<view class="num">
									<text class="price" v-if="item.STATE==2">¥{{item.SALEPRICE}}</text>
									<text class="price" v-else>该商品已下架</text>
									<view class="num-right" v-if="item.STATE==2" >
										<view class="down" @click="sub(item,index)">-</view>
										<text class="add">{{item.num}}</text>
										<view class="up" @click="add(item,index)">+</view>
									</view>
									
								</view>
								
								<!-- <uni-number-box 
									class="step"
									:min="1" 
									:max="item.salestock"
									:value="item.num>item.salestock?item.salestock:item.num"
									:isMax="item.num>=item.salestock?true:false"
									:isMin="item.num===1"
									:index="index"
									@eventChange="numberChange(item,index)"
								></uni-number-box> -->
							
							
							
							
							<!-- <uni-number-box 
								class="step"
								:min="1" 
								:max="item.salestock"
								:value="item.num>item.salestock?item.salestock:item.num"
								:isMax="item.num>=item.salestock?true:false"
								:isMin="item.num===1"
								:index="index"
								@eventChange="numberChange(item,index)"
							></uni-number-box> -->
							</view>
						</view>
							<text class="del-btn yticon icon-iconfontshanchu1" @click="deleteCartItem(item,index)"></text>
					</view>
				</block>
			</view>
			
			
			
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image 
						:src="allChecked?'/static/selected.png':'/static/select.png'" 
						mode="aspectFit"
						@click="check('all')"
					></image>
					<view class="clear-btn" :class="{show: allChecked}" @click="clearCart">
						清空
					</view>
				</view>
				<view class="total-box">
					<text class="price">¥{{total}}</text>
					<text class="coupon">
						已优惠
						<text>0.00</text>
						元
					</text>
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNoticeBar from '@/components/uni-notice-bar/uni-notice-bar.vue'
	import uniNumberBox from '@/components/uni-number-box.vue'
	export default {
		components: {
			uniNoticeBar,
			uniNumberBox
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				cartList1: [],
				cartListsid:'',
				cartListnum:'',
				img: ''
			};
		},
		onLoad(){
			this.img = getApp().globalData.imageAddress
			if(uni.getStorageSync("SIGNATURE")){
				this.loadData();
			}else{
				uni.request({
					url: getApp().globalData.http+'/common/regist', //仅为示例，并非真实接口地址。
					data: {
						BRAND : this.BRAND,
						MODEL : this.MODEL,
						OS : this.OS,
						OSVERSION: this.OSVERSION,
						SCREEN: this.SCREEN,
						RESOLUTION: this.RESOLUTION,
						MIDU: this.MIDU,
						UQID: this.UQID,
						OSID: this.OSID,
						TVERSION: this.TVERSION,
						TYPE: this.TYPE,//A.Android B.iPhone C.iPad
					},
					method:"POST",
					header: {
						'content-type':'application/x-www-form-urlencoded',
					},
					success: (res) => {
						uni.setStorageSync("SIGNATURE",res.data.OBJECT.SIGNATURE);
						this.loadData();
					}
				});
			}
			uni.startPullDownRefresh();
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onShow(){
			this.loadData();
		},
		watch:{
			//显示空白页
			cartList(e){
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		computed:{
			...mapState(['hasLogin'])
		},
		methods: {
			//请求数据
			async loadData(){
				let key = uni.getStorageSync('userInfo').USER == undefined ? 'card' : uni.getStorageSync('userInfo').USER.PHONE 
				
				
				console.log("key : ",key)
				let car = uni.getStorageSync(key)|| []
				if(car.length==0){
					this.cartList = [];
				}else{
					let date = [];
					date = uni.getStorageSync(key);
					this.cartListsid = []
					this.cartListnum = []
					date.forEach(item=>{
						this.cartListsid = this.cartListsid +","+ item.selectedid
						this.cartListnum = this.cartListnum +","+ item.num
					})
					this.cartListsid = this.cartListsid.substring(1,this.cartListsid.length)
					this.cartListnum = this.cartListnum.substring(1,this.cartListnum.length)
					console.log("66666",this.cartListsid)
					this.$http.post("/goods/cartList",{
						SIGNATURE : uni.getStorageSync("SIGNATURE"),
						TOKEN: uni.getStorageSync('userInfo').TOKEN,
						CIDS: this.cartListsid
					}).then((res) => {
						if(res.data.STATE == '903'||res.data.STATE == '904'){
							// #ifdef MP-WEIXIN
							uni.showModal({
								content:'请先登录',
								success: function (res) {
								        if (res.confirm) {
								            uni.switchTab({
								            	url:"/pages/user/user"
								            })
								        } else if (res.cancel) {
								            console.log('用户点击取消');
								        }
								    }
							})
							// #endif
							// #ifndef MP-WEIXIN
							uni.navigateTo({
								url: "/pages/public/login1"
							})
							// #endif
						}
						if (res.statusCode === 200 && res.data.STATE === '0') {  
							let sid = []
							let num = []
							sid = this.cartListsid.split(",")
							num = this.cartListnum.split(",")
							this.cartList = res.data.OBJECT.LIST.map(item=>{
								
								for(let i=0;i<sid.length;i++){
									
									if(parseInt(sid[i])==item.ID){
										item.num = parseInt(num[i])
										if(item.STATE == 2 ){
											item.checked = true;
										}
										if(item.STATE == 3){
											item.checked =false;
										}
										return item
									}
								}
							})
							this.calcTotal();  //计算总价
							console.log("*********",this.cartList)
							
						}else{
							uni.showToast({title:res.data.MSG, icon:"none"});
						}
					}).catch((err)=>{
						console.log('request fail', err);
					})
					
				}
				
			
			},
			see(id){
				uni.navigateTo({
					url: '/pages/product/product?id='+id
				})
			},
			// #ifdef MP-WEIXIN
			navToLoginWx(){
				uni.switchTab({
					url: '/pages/user/user'
				})
			},
			// #endif
			// #ifndef MP-WEIXIN
			navToLogin(){
				uni.navigateTo({
					url: '/pages/public/login1'
				})
			},
			// #endif
			
			 //选中状态处理
			check(type, index){
				if(type === 'item'){
					this.cartList[index].checked = !this.cartList[index].checked;
				}else{
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item=>{
						if(item.STATE!=3){
							item.checked = checked;
						}
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			//修改数量
			add(cart,index){
				if(cart.SALESTOCK>cart.num){
					let key = uni.getStorageSync('userInfo').USER.PHONE || 'card'
					let car = uni.getStorageSync(key)|| []
					let car1 = car.map(item=>{
						if(item.selectedid == cart.ID){
							item.num+=1
						}
						return item
					})
					uni.setStorage({
						key: key,
						data: car1
					})
					this.cartList[index].num = cart.num+1;
					this.calcTotal();
				}
			},
			sub(cart,index){
				if(cart.num>1){
					let key = uni.getStorageSync('userInfo').USER.PHONE || 'card'
					let car = uni.getStorageSync(key)|| []
					let car1 = car.map(item=>{
						if(item.selectedid == cart.ID){
							item.num-=1
						}
						return item
					})
					uni.setStorage({
						key: key,
						data: car1
					})
					this.cartList[index].num = cart.num-1;
					this.calcTotal();
				}else{
					this.deleteCartItem(cart,index)
				}
				
			},
			//删除
			deleteCartItem(cart,index){
				let key = uni.getStorageSync('userInfo').USER.PHONE || 'card'
				let car = []
				car= uni.getStorageSync(key)|| []
				let count = 0
				let count1 = 0
				car.forEach(item=>{
					count++
					if(item.selectedid == cart.ID){
						count1 = count
					}
				})
				if(car.length==1){
					car = []
				}else{
					car.splice(count1,1)
				}
				
				console.log(car)
				uni.setStorage({
					key: key,
					data: car
				})
				
				let list = this.cartList;
				let row = list[index];
				let id = row.id;
				
				this.cartList.splice(index, 1);
				
				this.calcTotal();
				uni.hideLoading();
			},
			//清空
			clearCart(){
				uni.showModal({
					content: '清空购物车？',
					success: (e)=>{
						if(e.confirm){
							let key = uni.getStorageSync('userInfo').USER.PHONE || 'card'
							uni.setStorage({
								key: key,
								data: []
							})
							this.cartList = [];
						}
					}
				})
				this.calcTotal()
			},
			//计算总价
			calcTotal(){
				let list = this.cartList;
				if(list.length === 0){
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				list.forEach(item=>{
					if(item.checked === true){
						total += item.SALEPRICE * item.num;
					}else if(checked === true){
						checked = false;
					}
				})
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder(){
				let list = this.cartList;
				let goodsData = [];
				list.forEach(item=>{
					if(item.checked && item.STATE==2){
						goodsData.push({
							id:item.GOODSID,
							num:item.num,
							SID:item.ID
						})
					}
				})
				if(goodsData.length>0){
					uni.navigateTo({
						url: `/pages/order/createOrderCart?data=${JSON.stringify(goodsData)}`
					})
					this.$api.msg('跳转下一页 sendData');
				}else{
					uni.showToast({
						title:"请选择有效商品",
						icon:"none"
					})
				}
				
			}
		}
	}
</script>

<style lang='scss'>
	.container{
		padding-top: 50upx;
		padding-bottom: 134upx;
		margin-left: 40upx;
		margin-right: 20upx;
		/* 空白页 */
		.empty{
			position:fixed;
			left: 0;
			top:0;
			width: 100%;
			height: 100vh;
			padding-bottom:100upx;
			display:flex;
			justify-content: center;
			flex-direction: column;
			align-items:center;
			background: #fff;
			image{
				width: 240upx;
				height: 160upx;
				margin-bottom:30upx;
			}
			.empty-tips{
				display:flex;
				font-size: $font-sm+2upx;
				color: $font-color-disabled;
				.navigator{
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}
		/* 购物车列表项 */
	
	.cart-list{
		margin-top: 20upx;
		background: #f5f5f5;
		
		.cart-item{
			border: 1upx solid #eaeaed;
			border-radius: 5%;
			background: #fff;
			display:flex;
			position:relative;
			padding:20upx 40upx;
			margin-bottom: 10upx;
			.image-war{
				background-color: #fff;
				width: 180upx;
				height: 160upx;
				flex-shrink: 0;
				position:relative;
				image{
					padding-top: 20upx;
					padding-left: 30upx;
					width: 180upx;
					height: 160upx;
					position:relative;
					border-radius:8upx;
				}
			}
			
			.checkbox{
				position:absolute;
				left:-26upx;
				top: 66upx;
				z-index: 8;
				font-size: 44upx;
				line-height: 1;
				padding: 4upx;
				color: $font-color-disabled;
				background:#fff;
				border-radius: 50px;
			}
			.item-right{
				display:flex;
				flex-direction: column;
				padding-left: 30upx;
				width: 400upx;
				.title,.price{
					
					margin-top: 20upx;
					color: $font-color-dark;
					height: 40upx;
					line-height: 40upx;
					font-size: 28upx;
				}
				.clamp{
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
				.num{
					display: flex;
					
					.num-right{
						display: flex;
						margin-top: 20upx;
						margin-left: 90upx;
						border: 1upx solid #F2F2F2;
					}
					.add{
						font-size:$font-base ;
						padding: 10upx;
						border: 1upx solid #F2F2F2;
					}
					.up{
						padding-right: 20upx;
						padding-left: 20upx;
						background-color: #F2F2F2;
					}
					.down{
						padding:0upx 26upx;
						background-color: #F2F2F2;
					}
				}
				.attr{
					
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					line-height: 40upx;
				}
				.price{
					font-size: 30upx;
					height: 40upx;
					line-height:40upx;
					color: #F76260;
				}
				.step{
					/* #ifndef H5 */
					/* 需条件编译的代码  除了H5  别的出现 */
					position:absolute;
					top:180upx;
					left: 380upx;
					/* #endif */
					/* #ifdef H5 */
					/* 需条件编译的代码  H5出现 */
					left: 400upx;
					top: 110upx;
					/* #endif */
					
				}
			}
			.del-btn{
				position:absolute;
				right: 20upx;
				top: 40upx;
				font-size:34upx; 
				color: #F76260;
			}
		}
	}
	
	/* 底部栏 */
	.action-section{
		/* #ifdef H5 */
		margin-bottom:150upx;
		/* #endif */
		position:fixed;
		left: 30upx;
		bottom:30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 690upx;
		height: 100upx;
		padding: 0 30upx;
		background: rgba(255,255,255,.9);
		box-shadow: 0 0 20upx 0 rgba(0,0,0,.5);
		border-radius: 16upx;
		.checkbox{
			height:52upx;
			position:relative;
			image{
				width: 52upx;
				height: 100%;
				position:absolute;
				left:5upx;
				z-index: 5;
			}
			.clear-btn{
				position:absolute;
				left: 26upx;
				top: 0;
				z-index: 4;
				width: 0;
				height: 52upx;
				line-height: 52upx;
				padding-left: 38upx;
				font-size: $font-base;
				color: #fff;
				background: $font-color-disabled;
				border-radius:0 50px 50px 0;
				opacity: 0;
				transition: .2s;
				&.show{
					opacity: 1;
					width: 120upx;
				}
			}
		}
		
		.total-box{
			flex: 1;
			display:flex;
			flex-direction: column;
			text-align:right;
			padding-right: 40upx;
			.price{
				font-size: $font-lg;
				color: $font-color-dark;
			}
			.coupon{
				font-size: $font-sm;
				color: $font-color-light;
				text{
					color: $font-color-dark;
				}
			}
		}
		.confirm-btn{
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			font-size: $font-base + 2upx;
			/* background: $uni-color-primary; */
			background: #E02E24;
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72)
		}
	}
	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked
	{
		color: $uni-color-primary;
	}
</style>
